<?php
/*
* DatabaseConnection.php
* Handles the connection to the MySQL-database and various prepared sqlstatements.
*/
class DatabaseConnection
{
	/*
	* Private membervariables.
	*/
	private $host = 'localhost';
	private $username = '';
	private $password = '';
	private $databaseName = '';	
	
	// MySqli-object that holds the connection to the database.
	private $mysqliObject = null;
	
	/*
	* Constructor
	* Saves the incoming databasename to the private members 'databaseName'
	* 
	* @param string $username Username to the database.
	* @param string $password Password to the database.
	* @param string $databaseName The name of the database to connect to.
	*/
	public function __construct($username, $password, $databaseName )
	{
		$this->username = $username;
		$this->password = $password;
		$this->databaseName = $databaseName;
	}
	
	/*
	* Connect
	* Creates a connection to the given database.
	*/
	public function Connect()
	{
		// Creates a new MySqli object with the given parameters.
		$this->mysqliObject = new mysqli( $this->host, $this->username, $this->password, $this->databaseName );
		
		// if the connection fails
		if ( mysqli_connect_errno() == true)
		{
			// Prints of the errors.
			printf( "Anslutningen misslyckades: %s\n", mysql_connect_error() );
			
			// Exits the connection.
			exit();
		}
	}
	
	/*
	* Close
	* Closes the connection to the database.
	*/
	public function close()
	{
		$this->mysqliObject->close();
	}
	
	/*
	* PrepareStatement
	* Prepares sqlstatements.
	* 
	* @param string $sqlStatement sqlStatements need to contain a sqlstatement ex: SELECT column FROM table WHERE name=?
	* @return mysqli a mysqli-preparedstatement to the database.
	*/
	public function PrepareStatement( $sqlStatement )
	{
		return $this->mysqliObject->prepare( $sqlStatement );
	}
	
	/**
	* Shows the affected rows for the last query to the database.
	* @return string the last affected row.
	*/
	public function AffectedRows()
	{
		return $this->mysqliObject->affected_rows;
	}
	
	/**
	* Shows any errors from the database.
	* @return String The error(s) from the latest query.
	*/
	public function GetMySQLError()
	{
		return $this->mysqliObject->error;
	}
}